import { defineStore } from 'pinia'

export const useTodos = defineStore('todo', {
  state: () => ({
    /** @type {{ text: string, id: number, isFinished: boolean }[]} */
    todos: [
      { text: 'string', id: 1, isFinished: true },
      { text: '打饭', id: 2, isFinished: false },
      { text: '大球', id: 3, isFinished: true }
    ],
    /** @type {text: string, id: number, isFinished: boolean } */
    todo: { text: 'string', id: 1, isFinished: true },
    /** @type {'all' | 'finished' | 'unfinished'} */
    filter: 'all',
    // 类型将自动推断为 number
    nextId: 0,
    /** @type {true| false } */
    dialogFormVisible: true
  }),
  getters: {
    allTodos(state) {
      return state.todos
    },
    finishedTodos(state) {
      // 自动补全！ ✨
      return state.todos.filter((todo) => todo.isFinished)
    },
    unfinishedTodos(state) {
      return state.todos.filter((todo) => !todo.isFinished)
    },
    /**
     * @returns {{ text: string, id: number, isFinished: boolean }[]}
     */
    filteredTodos(state) {
      console.log(state)
      if (this.filter === 'finished') {
        // 调用其他带有自动补全的 getters ✨
        return this.finishedTodos
      } else if (this.filter === 'unfinished') {
        return this.unfinishedTodos
      }
      return this.todos
    }
  },
  actions: {
    // 接受任何数量的参数，返回一个 Promise 或不返回
    addTodo() {
      // 你可以直接变更该状态
      this.todos.push(JSON.parse(JSON.stringify(this.todo)))
    }
  }
})
